<?php

namespace app\modules\chat\controllers;

use Yii;
use yii\web\Controller;
use common\models\Tools;
use common\models\Chat;
use \common\models\ChatMsg;

/**
 * Default controller for the `chat` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        $this->layout = "/chat";
        $chatid = Tools::GetSafeParam('chatid', 0, 0);
        //登录检测
        if (Yii::$app->user->isGuest) {
            return $this->redirect('/site/login?returnurl=/chat/'.$chatid);
        }
        //检测会话合法性
        
        $chat = Chat::findOne(['id'=>$chatid]);
        $userid = Yii::$app->user->identity->id;
        if($chat->user1 != $userid && $chat->user2 != $userid){
            return $this->redirect('/');
        }
        
        $my_headimg = empty(Yii::$app->user->identity->headimg) ? '/img/user/default-head.png' : Yii::$app->user->identity->headimg;
        //获取好友信息
        $friendid = ($chat->user1 == $userid) ? $chat->user2 : $chat->user1;
        //好友名称 头像
        $friend = \common\models\User::findOne(['id'=>$friendid]);
        
        $friend_headimg = empty($friend->headimg) ? '/img/user/default-head.png' : $friend->headimg;
        //获取历史消息
        $history = ChatMsg::getHistoryMsg($chatid);
        
        //设置消息为已读
        ChatMsg::setToReaded($chatid,$userid);
        
        return $this->render('index',['chatid'=>$chatid,'my_headimg'=>$my_headimg,'my_name'=>Yii::$app->user->identity->username,'friend_headimg'=>$friend_headimg,'friend_name'=>$friend->username,'friend_id'=>$friend->id,'history'=>$history]);
    }
}
